﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using HZ.MBSM.DBUtility;
using HZ.MBSM.BLL;
public partial class Bidder_Tra_BidPlanList : System.Web.UI.Page, HZ.MBSM.BLL.TraDes
{
    string Accountid_PS;
    //string BuyPlanId = "";
    public string Qdataoutflow = "", Showout = "none";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HZ.MBSM.BLL.Login.CheckAssert(this.UseAccountType))
        {
            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            Accountid_PS = _Account.AccountId.ToString();
            //  _strProjectId = SysFun.ToTrim(Request.QueryString["ProjectId"]);  2007/08/22 马


            //SelecteBuyPlanId();//查找采购单号
            if (!IsPostBack)
            {
                listDealStatus.Items.Add("全部");
                listDealStatus.Items.Add("未确认送货");
                listDealStatus.Items.Add("已确认送货");
                listDealStatus.Items.Add("医院已入库");
                listDealStatus.Items.Add("企业无法送货");
                listDealStatus.Items.Add("已删除");
                listDealStatus.Items.Add("到期未送货");
                listDealStatus.SelectedIndex = 1;
                ///////////////////////////////////////
                listSN.Items.Add("全部");
                listSN.Items.Add("确认量小于采购量");
                listSN.Items.Add("采购量小于确认量");
                listSN.SelectedIndex = 0;

            }
            //<!--确定配送

            if (Request.Form["submitSave"] == "确定配送" && Request.Form["chk"] != null)
            {
                string _strBuyPlanGoodsId = SysFun.ToTrim(Request.Form["chk"]);

                Db db = new Db();
                if (_strBuyPlanGoodsId != "")
                {
                    string[] _strArrayBuyPlanGoodsId = _strBuyPlanGoodsId.Length == 0 ? new string[] { "" } : _strBuyPlanGoodsId.Substring(0).Split(new char[] { ',' });

                    string _strSql = "";
                    for (int i = 0; i < _strArrayBuyPlanGoodsId.Length; i++)
                    {
                        string _strinfownm = SysFun.ToTrim(Request.Form["batchnum" + _strArrayBuyPlanGoodsId[i].ToString()]);
                        if (SysFun.IsNumeric(_strinfownm) && Convert.ToInt32(_strinfownm) >= 0)
                        {
                            int j = Convert.ToInt32(_strinfownm) == 0 ? 4 : 1;// 确认量为0 这置为无法配送 》0 则为确认
                            _strSql += "@" + "update BuyPlanGoods set DealStatus='" + j + "',CompanyInflowDate=getdate(),InflowNum=" + _strinfownm + "  where DealStatus=0 and BuyPlanGoodsId=" + _strArrayBuyPlanGoodsId[i].ToString();
                        }
                    }
                    if (_strSql.Length > 0)
                    {
                        HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "BuyPlanGoods", _strSql, "../Bidder/Tra_BidPlanList.aspx");
                        db.ExecuteTransaction(_strSql.Substring(1).Split(new char[] { '@' }), 30);

                    }
                    //  db.Command("update PurchasePlan set memo1=1 where  BuyPlanId in (select BuyPlanId from BuyPlanGoods where projectid=" + _strProjectId + " group by BuyPlanId having sum(case DealStatus when 0 then 1 else 0 end ) =0) and memo1 is null");
                    // 2007/08/22  马

                    db.Command("update PurchasePlan set memo1=1 where  BuyPlanId in (select BuyPlanId from BuyPlanGoods  group by BuyPlanId having sum(case DealStatus when 0 then 1 else 0 end ) =0) and memo1 is null");
                    HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "PurchasePlan", _strSql, "../Bidder/Tra_BidPlanList.aspx");
                }

                db.Close();
                //确定配送-->
            }
            //<!--确定配送

            if (Request.Form["submitSave"] == "无法配送" && Request.Form["chk"] != null)
            {
                string _strBuyPlanGoodsId = SysFun.ToTrim(Request.Form["chk"]);
                Response.Write("<script> window.open('TraNoPS.aspx?BId=" + _strBuyPlanGoodsId + "&id=0')</script>");
            }
            showGridView();
            ShowMesg(Accountid_PS);

        }

    }




    /// <summary>
    /// 绑定需要打印的数据源

    /// </summary>
    private void getPrintSource()
    {
        string sql = "select BuyPlanId as 采购单号,GoodsId as 商品流水号,productname as 通用名,goodsname as 商品名,medicinemodel as 剂型,outlookc as 规格,factor as 转换系数," +
            "Outlookc+'×'+convert(varchar(20),Factor)+unit As 包装规格,QualityLevels as 质量层次,TradePrice as 交易价,GoodsNum as 采购数量," +
            "HospitalName as 采购医院,CompanyName_SC as 生产企业,UserCode_SC as 生产企业注册号,Case DealStatus When '0' Then '未确认' When '1' Then '确认送货' When '2' Then '医院已入库' When '4' Then '企业无法送货' When '6' Then '已删除' END AS 处理状态," +
            "('建单时间：' + convert(varchar(10),BuildTime,120)+ ' 开始时间：' + convert(varchar(10),StartTime,120)+' 结束时间：'" +
            "+ convert(varchar(10),EndTime,120)) as 详情" +
            " from BuyGoodsView_200708 where ";
        sql += fctConditions();
        sql += " order by StartTime ,ProductName,MedicineModel,Outlookc,CompanyName_SC,BuyPlanGoodsId";
        Db db = new Db();
        DataTable dt = db.DataTable(sql);
        this.gvList.DataSource = dt;
        this.gvList.DataBind();
        db.Close();
    }

    /// <summary>
    /// 保存为excel文件
    /// </summary>
    private void ImportExcel()
    {
        getPrintSource();
        if (gvList.Rows.Count > 0)
        {
            gvList.Visible = true;
            Response.Clear();
            Response.ContentType = "application/x-excel";
            Response.AddHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode("配送单" + DateTime.Now.ToShortDateString(), System.Text.Encoding.UTF8) + ".xls\"");
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            StringBuilder sb = new StringBuilder();
            System.IO.StringWriter stringWrite = new System.IO.StringWriter(sb);
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            sb.Append(@"<style> .text { mso-number-format:\@; } </style> ");
            sb.Append("<html><body>");
            gvList.RenderControl(htmlWrite);
            sb.Append("</body></html>");
            Response.Write(stringWrite.ToString());
            Response.End();
            gvList.DataSource = null;
            gvList.Dispose();
        }
        else
        {
            Response.Write("<script>alert('没有信息,无法打印!')</script>");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
    }

    public void showGridView()
    {
        int i = 0;
        string _strcolor = "White"; //默认背景为白色
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        string _strWhere = fctConditions();
        dbPage.Table = "BuyGoodsView_200708 ";                                               //要查询的表明
        dbPage.Key = "BuyPlanGoodsId";                                               //表的主键                                                                                                                                                                                                //DealStatus When '0' Then '未确认' WHEN '1' Then '确认送货' WHEN '2' then '确认入库' WHEN '3' then '退货'
        dbPage.Where = _strWhere;                                          //查询条件    
        dbPage.SelectField = "StartTime,EndTime,BuildTime,UserCode,HospitalName,BuyPlanGoodsId,InflowNum,GoodsNum,BuyPlanId,SupplyGoodsId,GoodsId,ProductCode,ProductName,MedicineModel,Outlookc,BuyGoodsView_200708.ProjectId,Factor,CompanyName_SC,UserCode_SC,CompanyName_TB,TradePrice,Case DealStatus When '0' Then '未确认' When '1' Then '确认送货' When '2' Then '医院已入库' When '4' Then '企业无法送货' When '6' Then '已删除' END AS DealStatus,GoodsName,isnull(Outlookc,'')+'×'+convert(varchar(50),Factor)+'/'+Unit As Pack1,QualityLevels,batchnumber,validityDate";//要显示的字段
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        dbPage.PageSize = 30;                                                    //没有显示记录条数   
        dbPage.OrderBy = "StartTime ,ProductName,MedicineModel,Outlookc,CompanyName_SC,BuyPlanGoodsId";//排序字段
        System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
        strHtml.Append("<table width='98%' border='0' align='center' cellpadding='2' cellspacing='1' class='table_table'>");
        strHtml.Append("<tr>");
        strHtml.Append("<td  class='table_title' >采购<br>单号</td>");
        strHtml.Append("<td  class='table_title' width='8%'>商品<br/>流水号</td>");
        strHtml.Append("<td  class='table_title' width='8%'>通用名</td>");
        strHtml.Append("<td  class='table_title' width='5%'>商品名</td>");
        strHtml.Append("<td  class='table_title' nowrap>剂型</td>");
        strHtml.Append("<td  class='table_title' >包装<br/>规格</td>");
        //  strHtml.Append("<td  class='table_title'>质量<br/>层次</td>");
        strHtml.Append("<td  class='table_title'>交易价</td>");
        strHtml.Append("<td  class='table_title'>采购量</td>");
        strHtml.Append("<td  class='table_title'>确认量</td>");
        //strHtml.Append("<td  class='table_title'>药品<br/>批号</td>");
        // strHtml.Append("<td  class='table_title'>药品<br/>有效期</td>");
        strHtml.Append("<td  class='table_title'>采购医院</td>");
        strHtml.Append("<td  class='table_title' width='9%'>生产企业</td>");
        //  strHtml.Append("<td  class='table_title' >生产企业<br/>注册号</td>");

        strHtml.Append("<td  class='table_title'>处理状态</td>");
        strHtml.Append("<td  class='table_title' width='10%'>详情</td>");
        strHtml.Append("<td  class='table_title' nowrap>选择</td>");
        strHtml.Append("</tr>");
        System.Data.IDataReader dr = dbPage.ExecuteReader();

        while (dr.Read())
        {
            if (SysFun.ToTrim(dr["DealStatus"]) == "未确认")
            {
                _strcolor = Companttiem(dr["EndTime"].ToString());//时间差的颜色
            }
            if (i == 0)
            {
                strHtml.Append("<tr class='table_td'  style=\"background-color:" + _strcolor + "\">");
                i++;
            }
            else
            {
                strHtml.Append("<tr class='table_td2' style=\"background-color:" + _strcolor + "\">");
                i--;
            }
            strHtml.Append("<td><a href='PurchaseDeal_detail.aspx?BuyPlanId=" + dr["BuyPlanId"].ToString() + "'title='查看联系人' target=_blank>" + dr["BuyPlanId"].ToString() + "</a></td>");
            strHtml.Append("<td>" + dr["GoodsId"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["ProductName"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["GoodsName"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["Medicinemodel"].ToString() + "</td>");

            strHtml.Append("<td>" + dr["Pack1"].ToString() + "</td>");
            // strHtml.Append("<td>" + dr["QualityLevels"].ToString() + "</td>");
            strHtml.Append("<td>" + SysFun.OutNum(dr["TradePrice"].ToString(), 2) + "</td>");
            strHtml.Append("<td>" + SysFun.ToTrim(dr["GoodsNum"]) + "</td>");
            if (SysFun.ToTrim(dr["DealStatus"]) == "未确认")
            {
                strHtml.Append("<td ><input type='text' id='batchnum" + dr["BuyPlanGoodsId"].ToString() + "' name='batchnum" + dr["BuyPlanGoodsId"].ToString() + "' value='" + SysFun.ToTrim(dr["GoodsNum"]) + "' style='width: 60px' onblur=\"javascript:if(!/^\\+?[0-9][0-9]*$/.test(this.value)){alert('请输入正确的数量！');this.value=" + SysFun.ToTrim(dr["GoodsNum"]) + "};if(this.value>" + SysFun.ToTrim(dr["GoodsNum"]) + "){alert('对不起,你输入的确认量大于采购量！');this.value=" + SysFun.OutNum(dr["GoodsNum"].ToString(), 2) + "}\" NumericOnly='InflowNum' NotNull='InflowNum' ></td>");
            }
            else
            {
                strHtml.Append("<td>&nbsp;" + dr["InflowNum"].ToString() + "</td>");
            }
            //if (SysFun.ToTrim(dr["DealStatus"]) == "未确认")
            //{
            //    strHtml.Append("<td><input type='text' id='batchnum" + dr["BuyPlanGoodsId"].ToString() + "' name='batchnum" + dr["BuyPlanGoodsId"].ToString() + "' value=''></td>");
            //}
            //else
            //{
            //    strHtml.Append("<td>&nbsp;"+dr["batchnumber"].ToString() + "</td>");
            //}

            //if (SysFun.ToTrim(dr["DealStatus"]) == "未确认")
            //{
            //    strHtml.Append("<td><input type='text' id='validityDate" + dr["BuyPlanGoodsId"].ToString() + "' name='validityDate" + dr["BuyPlanGoodsId"].ToString() + "' value=''onclick='javascript:fPopCalendar(this,this);'></td>");
            //}
            //else
            //{
            //    strHtml.Append("<td>&nbsp;"+ dr["validityDate"].ToString() + "</td>");
            //}

            strHtml.Append("<td>" + SysFun.ToTrim(dr["HospitalName"]) + "</td>");
            strHtml.Append("<td>" + dr["CompanyName_SC"].ToString() + "</td>");
            //   strHtml.Append("<td>" + dr["UserCode_SC"].ToString() + "</td>");

            if (dr["DealStatus"].ToString() == "企业无法送货")
            {
                strHtml.Append("<td ><a href=# onClick=\"javascript:window.open('../Bidder/TraNoPS.aspx?BId=" + dr["BuyPlanGoodsId"].ToString() + "','','width=670,height=250,toolbar=no, status=no, menubar=no, resizable=yes, scrollbars=yes');return false;\" target='_blank'><font color='ff0000'>" + dr["DealStatus"].ToString() + "</font></a></td>");
            }
            else
            {
                strHtml.Append("<td >" + dr["DealStatus"].ToString() + "</td>");
            }
            //  strHtml.Append("<td  width='10%'> 建单时间：" + ((DateTime)dr["BuildTime"]).ToString("yyyy-MM-dd") + " \n 开始时间：" + ((DateTime)dr["StartTime"]).ToString("yyyy-MM-dd") + "\n 结束时间：" + (string.Format("{0:yyyy-MM-dd}", dr["EndTime"])) + "</td>");
            strHtml.Append("<td style=\" text-align:center\" onmouseover=\"this.oldcolor=this.style.backgroundColor;this.style.backgroundColor='#c8f7ff'\"  onmousemove=\"show('" + ((DateTime)dr["BuildTime"]).ToString("yyyy-MM-dd HH:mm:ss") + "','" + ((DateTime)dr["StartTime"]).ToString("yyyy-MM-dd HH:mm:ss") + "','" + (string.Format("{0:yyyy-MM-dd HH:mm:ss}", dr["EndTime"])) + "')\" onmouseout=\"this.style.backgroundColor=this.oldcolor;hide();\">移上鼠标</td>");
            if (SysFun.ToTrim(dr["DealStatus"]) != "未确认")
            {
                strHtml.Append("<td></td>");
            }
            else
            {
                strHtml.Append("<td><input name='chk' type='checkbox' value='" + dr["BuyPlanGoodsId"].ToString() + "'></td>");
            }
            strHtml.Append("</tr>");
        }
        strHtml.Append("</table>");
        Lablist.Text = strHtml.ToString();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        dr = null;
        db = null;
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键

    }

    /// <summary>
    /// 生成查询条件
    /// </summary>
    /// <returns></returns>
    public string fctConditions()
    {

        // string _strTemp = " BuyGoodsView.ProjectId=" + _strProjectId + "  and Accountid_PS=" + Accountid_PS + " and BuyStatus=2 and",
        //_strProductName, _strMedicinemodel, _strOutlookc, _strGoodsName, _GoodsId, _strCompanyNameSC, _UserCodeSC,_strHospital,_strHospitalcode;
        // 2007/08/22 马

        string _strTemp = " Accountid_PS=" + Accountid_PS + " and BuyStatus=2 and",
           _strProductName, _strMedicinemodel, _strOutlookc, _strGoodsName, _GoodsId, _strCompanyNameSC, _UserCodeSC, _strHospital, _strHospitalcode, _strProductNameX;

        //采购单号
        string _strBuyPlanId = txtBuyPlanId.Text;
        if (_strBuyPlanId != "")
        {
            _strTemp += "  BuyPlanId=" + _strBuyPlanId + "  and";
        }
        //通用名

        _strProductName = txtProductName.Text.ToString().Trim();
        if (_strProductName != "")
        {
            _strTemp += "   ( ProductName like '%" + _strProductName + "%' or Product_SpellingCode like '%" + _strProductName + "%' )  and";
        }
        //通用名

        _strProductNameX = TextBox1.Text.ToString().Trim();
        if (_strProductNameX != "")
        {
            _strTemp += "   ( ProductName = '" + _strProductNameX + "' or Product_SpellingCode = '" + _strProductNameX + "' )  and";
        }

        //剂型
        _strMedicinemodel = txtMedicinemodel.Text.ToString().Trim();
        if (_strMedicinemodel != "")
        {
            _strTemp += " medicinemodel like '%" + _strMedicinemodel + "%' and";
        }

        //规格
        _strOutlookc = txtOutlook.Text.ToString().Trim();
        if (_strOutlookc != "")
        {
            _strTemp += " outlookc like '%" + _strOutlookc + "%' and";
        }

        //商品名

        _strGoodsName = txtGoodsName.Text.ToString().Trim();
        if (_strGoodsName != "")
        {
            _strTemp += " goodsname like '%" + _strGoodsName + "%' and";
        }

        //商品流水号

        _GoodsId = txtGoodsId.Text.ToString().Trim();
        if (_GoodsId != "")
        {
            _strTemp += " GoodsId =" + _GoodsId + " and";
        }

        //生产企业名称
        _strCompanyNameSC = txtCompanyNameSC.Text.ToString().Trim();
        if (_strCompanyNameSC != "")
        {
            _strTemp += " CompanyName_SC like '%" + _strCompanyNameSC + "%' and";
        }

        //生产企业编码
        _UserCodeSC = txtUserCodeSC.Text.ToString().Trim();
        if (_UserCodeSC != "")
        {
            _strTemp += " UserCode_SC like '%" + _UserCodeSC + "%' and";
        }
        //医院名称
        _strHospital = TextHospital.Text.ToString().Trim();
        if (_strHospital != "")
        {
            _strTemp += " HospitalName like '%" + _strHospital + "%' and";
        }
        //医院注册号

        _strHospitalcode = TextHospitalcode.Text.ToString().Trim();
        if (_strHospitalcode != "")
        {
            _strTemp += " UserCode like '%" + _strHospitalcode + "%' and";
        }

        //配送状态
        //DealStatus When '0' Then '未确认' WHEN '1' Then '确认送货' WHEN '2' then '确认入库' WHEN '3' then '退货'
        string _strDealStatus = listDealStatus.SelectedValue;
        switch (_strDealStatus)
        {
            case "全部":
                break;
            case "未确认送货":
                _strTemp += " DealStatus=0 and";
                break;
            case "已确认送货":
                _strTemp += " DealStatus=1 and";
                break;
            case "医院已入库":
                _strTemp += " DealStatus=2 and";
                break;

            case "企业无法送货":
                _strTemp += " DealStatus=4 and";
                break;
            case "已删除":
                _strTemp += " DealStatus=6 and";
                break;
            case "到期未送货":
                _strTemp += " DealStatus=1 and EndTime<GETDATE() and";
                break;
        }

        //供求关系
        string _strSN = listSN.SelectedValue;
        switch (_strSN)
        {
            case "全部":
                break;
            case "确认量小于采购量":
                _strTemp += " isnull(goodsnum,0)>isnull(inflownum,0) and";
                break;
            case "采购量小于确认量":
                _strTemp += " isnull(goodsnum,0)<isnull(inflownum,0) and";
                break;
        }

        if (_strTemp != "")
        {
            _strTemp = "  " + _strTemp.Substring(0, _strTemp.Length - 3);
        }

        return _strTemp;

    }

    //比较时间
    /// <summary>
    /// 比较时间
    /// </summary>
    /// <param name="time1">要比较的时间</param>
    /// <returns>返回当前时间和传入是的天数对应颜色</returns>
    private string Companttiem(string time1)
    {
        DateTime nowdate = DateTime.Now;
        DateTime dtie = DateTime.Parse(time1);
        TimeSpan ts = dtie.Subtract(nowdate);
        if (ts.TotalHours > 48) //2天以上的 无色
        {
            return "White";
        }
        else if (ts.TotalHours > 24) // 1< 天数<2 粉红
        {
            return "Fuchsia";
        }
        else if (ts.TotalHours > 0) //一天的红色
        {
            return "red";
        }
        else  //过期的 黑色
        {
            return "Black";
        }

    }
    /// <summary>
    /// 显示弹出对话框
    /// </summary>
    private void ShowMesg(string _Accountid_PS)
    {
        Tra_BidPlan mTra_BidPlan = new Tra_BidPlan();
        string _strnumer = mTra_BidPlan.Bidder_Tra_BidPlanListdatanotinflow(_Accountid_PS);

        if (Convert.ToInt32(_strnumer) > 0)
        {
            Qdataoutflow = _strnumer; Showout = "block";
        }
        else
        {
            Showout = "none"; Qdataoutflow = "0";
        }
    }

    #region TraDes 成员

    public string Name
    {
        get { return "采购药品确认"; }
    }

    public string Describe
    {
        get { return ""; }
    }

    public string ParentName
    {
        get { return "配送管理"; }
    }

    public System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> UseAccountType
    {
        get
        {
            System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);
            return _AccountType;
        }
    }

    #endregion


    protected void btnPrint_Click(object sender, EventArgs e)
    {
        ImportExcel();
    }
}
